package com.pri.chat.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.StatusBarUtil;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.DTBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.R;
import com.pri.chat.activity.PaiHangBangActivity;
import com.pri.chat.activity.ReleaseVideoActivity;
import com.pri.chat.activity.vedio.DetailActivity2;
import com.pri.chat.adapter.VideoListAdapter1;
import com.pri.chat.model.DTModel;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.StaggeredDividerItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxui.fragment.FragmentLazy;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author wx5e48d604c2885118
 * @time 2020/4/7
 */
public class VideoFragment1 extends FragmentLazy {
    private static final String TAG = "VideoFragment";
    Unbinder unbinder;
    @BindView(R.id.rec_main)
    RecyclerView recMain;
    @BindView(R.id.iv_release)
    ImageView ivRelease;
    @BindView(R.id.iv_paihangbang)
    ImageView iv_paihangbang;
    @BindView(R.id.srl_main)
    SmartRefreshLayout srlMain;


    private int type;
    private List<DTBean> mList;
    private VideoListAdapter1 mAdapter;
    private boolean isShowDialog = true;
    private int page = 1;
    private int mPosition;


    @Override
    protected View initViews(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstanceState) {
        View view = layoutInflater.inflate(R.layout.fragment_video_layout1, viewGroup, false);
        unbinder = ButterKnife.bind(this, view);
        initLayout();
        initSrl();
        return view;
    }

    public void deleteVedio(DTBean dt){
        mList.remove(dt);
        mAdapter.notifyDataSetChanged();
    }

    public void updateVedio(DTBean dt){
        for(int i=0;i<mList.size();i++){
            if(dt.getId().equals(mList.get(i).getId())){
                mList.set(i,dt);
                mAdapter.notifyDataSetChanged();
                break;
            }
        }
    }

    private void initSrl() {
        srlMain.setEnableLoadmoreWhenContentNotFull(false);
        srlMain.setOnRefreshListener(refresh_layout -> {
            refresh_layout.finishRefresh(500);
            refresh();
        });
        srlMain.setOnLoadmoreListener(refresh_layout -> {
            refresh_layout.finishLoadmore(500);
            isShowDialog = false;
            page++;
            initData();
        });
    }

    private void refresh() {
        mList.clear();
        mAdapter.notifyDataSetChanged();
        page = 1;
        isShowDialog = false;
        initData();
    }

    @Override
    protected void onVisible() {
        super.onVisible();
        StatusBarUtil.setTranslucentForImageViewInFragment(mContext,0,getView());
        StatusBarUtil.setLightMode(mContext);

    }

    /**
     * 初始化视频布局
     */
    private void initLayout() {
        mList = new ArrayList<>();

//        final StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
//        recMain.setLayoutManager(layoutManager);
//        recMain.setItemAnimator(null);
        final StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        //防止Item切换
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        recMain.setLayoutManager(layoutManager);
        final int spanCount = 2;
        recMain.addItemDecoration(new StaggeredDividerItemDecoration(mContext,3,spanCount));
        //解决底部滚动到顶部时，顶部item上方偶尔会出现一大片间隔的问题
        recMain.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                int[] first = new int[spanCount];
                layoutManager.findFirstCompletelyVisibleItemPositions(first);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && (first[0] == 1 || first[1] == 1)) {
                    layoutManager.invalidateSpanAssignments();
                }
            }
        });
        mAdapter = new VideoListAdapter1(R.layout.item_video1, mList);
        recMain.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(mContext, DetailActivity2.class);
                intent.putExtra("position",position);
                intent.putExtra("list",(Serializable) mList);
                intent.putExtra("page",page);
                startActivity(intent);
//                RxActivityTool.skipActivity(getContext(), NicePlayer.class);
            }
        });
    }

    private String pathDirs = Environment.getExternalStorageDirectory()+"/com.pri.chat/cache/video/";
    @Override
    protected void initData() {
        SubscriberOnNextListener<BaseBean<List<DTBean>>> onNextListener = baseBean -> {
            if (baseBean.getData().isEmpty() && page == 1) {
                mAdapter.notifyDataSetChanged();
            } else {
                mList.addAll(baseBean.getData());
                mAdapter.notifyDataSetChanged();
            }
        };
        String lat = SharedHelper.readValueByKeyForString(mContext, "lat");
        String lng = SharedHelper.readValueByKeyForString(mContext, "lng");
        DTModel dtModel = new DTModel(page, 1, SharedHelper.readId(mContext), lat, lng,null,null);//登录上传参数
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(dtModel));
        HttpMethods.getInstance().listVedio(new ProgressSubscriber<>(onNextListener, mContext, isShowDialog), requestBody);
    }

    @OnClick({R.id.iv_release,R.id.iv_paihangbang})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_release:
                RxActivityTool.skipActivity(mContext, ReleaseVideoActivity.class);
                break;
            case R.id.iv_paihangbang:
                RxActivityTool.skipActivity(mContext, PaiHangBangActivity.class);
                break;

        }
    }

}
